using System;
using System.Collections.Generic;
using UnityEngine;

public abstract class BatchProcessor : MonoBehaviour
{
    protected int m_curReqStockIndex;
    protected List<StockData> m_curReqStocks;
    public int fetchStocksCount = 0;
    protected float actionInterval;
    public Action<float> onProgress;
    public Action<string> onEnd;
    public void DoActionToAllStocks(Action<StockData> action)
    {
        m_toStop = false;
        m_curReqStockIndex = 0;
        m_curReqStocks = new List<StockData>( StocksDataController.instance.allStocks);
        if (fetchStocksCount > 0)
            m_curReqStocks = m_curReqStocks.GetRange(0, fetchStocksCount);
        
        DoActionToCurStock(action);
    }

    public void DoActionToCurStock(Action<StockData> action)
    {
        if (m_curReqStockIndex >= m_curReqStocks.Count)
        {
            Debug.Log("结束");
            onCompleted();
            return;
        }
        action?.Invoke(this.m_curReqStocks[m_curReqStockIndex]);
        
        if (m_toStop) 
            return;
        
        m_curReqStockIndex++;
        DoActionDelay.DelayAction(actionInterval, ()=>DoActionToCurStock(action));
        onProgress?.Invoke((float)m_curReqStockIndex/m_curReqStocks.Count);
    }

    private bool m_toStop;
    public void StopDoActions()
    {
        m_toStop = true;
        Debug.Log("to stop");
    }

    protected virtual void onCompleted()
    {
        onEnd?.Invoke("");
    }
}